package no.ntnu.fp.controllers;

import java.util.ArrayList;

import no.ntnu.fp.console.Options;
import no.ntnu.fp.model.User;
import no.ntnu.fp.storage.DBConnection;

public class UserController extends AbstractController {
	private ArrayList<String[]> users;
	private Options options;
	
	public UserController(Options options) {
		users = new ArrayList<String[]>();
		this.options = options;
		getUsersFromDatabase();
	}
	
	public void addUserToDatabase(String username, String passord, String firstname, String lastname, String birthdate) {
		User user = new User(username, passord, firstname, lastname, birthdate);
		user.save();
	}

	private void getUsersFromDatabase() {
		DBConnection db = new DBConnection();
		
		String query = String.format("select brukernavn,passord from Ansatt");
		setResultSet(db.makeSingleQuery(query));
		beforeFirst();
		while (next()) {
			String brukernavn = getString("brukernavn");
			String passord = getString("passord");
			String[] bruker = {brukernavn, passord};
			users.add(bruker);
		}
		
		if(isAfterLast())
			options.messageDialog("Du er tilkoblet databasen, og hentingen av brukernavn og passord var vellykket!");
		closeDBConnection(db);
	}

	public String[] getUserListWithoutPasswords() {
		String[] userArray = new String[users.size()];
		
		int i = 0;
		for (String[] user : users) {
			userArray[i] = user[0];
			i++;
		}
		
		return userArray;
	}

	public boolean isValid(String[] loginDetails) {
		for (String[] userDetails : users) {
			if (userDetails[0].equals(loginDetails[0]) && userDetails[1].equals(loginDetails[1]))
				return true;
		}
		return false;
	}
}
